<script setup>
import { inject, ref } from 'vue'
const { map, scene } = inject('mapScene') // scene 是 ref

import NavigationControl from '@mapbox/mapbox-gl-directions/dist/mapbox-gl-directions.js'
import '@mapbox/mapbox-gl-directions/dist/mapbox-gl-directions.css'
import { useCityLayers } from '@/composable/useCityLayers' // 新增导入

const showNavigation = ref(false)
let navControl = null
function toggleNavigation() {
  showNavigation.value = !showNavigation.value
  if (!map.value) return
  if (showNavigation.value) {
    navControl = new NavigationControl()
    map.value.addControl(navControl, 'top-left')
  } else {
    map.value.removeControl(navControl)
  }
}

// 下拉与图层逻辑
const showLayerDropdown = ref(false)
const layerEntries = ref([]) // [{ name, present }]

const { addBuildingLayer, addRoadsLayer, removeLayerByName, created } = useCityLayers()

function refreshLayerList() {
  const s = scene?.value
  if (!s || typeof s.getLayers !== 'function') {
    layerEntries.value = []
    return
  }
  const raw = s.getLayers() || []
  layerEntries.value = raw
    .map((l, i) => {
      const name = l.name ?? l.getName?.() ?? `layer-${i}`
      return { name, present: true }
    })
    [
      // 确保可切换的图层名也出现在列表（即使还没创建）
      ('building', 'roads')
    ].forEach((n) => {
      if (!layerEntries.value.some((e) => e.name === n))
        layerEntries.value.push({ name: n, present: !!created[n] })
    })
}

async function toggleLayerEntry(entry) {
  const s = scene?.value
  if (!s) return
  // 如果已在 scene 中，则移除；否则添加
  const exists = (s.getLayers() || []).some(
    (l) => l.name === entry.name || l.getName?.() === entry.name,
  )
  if (exists) {
    removeLayerByName(s, entry.name)
  } else {
    if (entry.name === 'building') await addBuildingLayer(s)
    if (entry.name === 'roads') await addRoadsLayer(s)
  }
  // 刷新列表
  refreshLayerList()
}

function onLayerBtn() {
  showLayerDropdown.value = !showLayerDropdown.value
  if (showLayerDropdown.value) refreshLayerList()
}
</script>

<template>
  <div class="top-area">
    <header class="header">
      <div class="logo">...</div>
      <div class="nav-buttons">
        <button class="btn menu" title="菜单">...</button>

        <!-- 原来的图层按钮 -->
        <div style="position: relative">
          <button class="btn layer" title="图层" @click="onLayerBtn">
            <i class="iconfont icon-ditu-youxia-tuceng"></i>
          </button>

          <!-- 下拉列表放在 TopArea 中 -->
          <div
            v-if="showLayerDropdown"
            class="layer-dropdown"
            style="
              position: absolute;
              right: 0;
              top: 64px;
              background: #0b1220;
              color: #fff;
              padding: 10px;
              border-radius: 6px;
              min-width: 180px;
              z-index: 30;
            "
          >
            <ul style="list-style: none; padding: 0; margin: 0">
              <li
                v-for="entry in layerEntries"
                :key="entry.name"
                style="
                  display: flex;
                  align-items: center;
                  justify-content: space-between;
                  padding: 6px 4px;
                "
              >
                <span>{{ entry.name }}</span>
                <input
                  type="checkbox"
                  :checked="entry.present"
                  @change="() => toggleLayerEntry(entry)"
                />
              </li>
            </ul>
            <div style="margin-top: 8px; display: flex; gap: 8px">
              <button
                @click="
                  async () => {
                    await addBuildingLayer(scene.value)
                    refreshLayerList()
                  }
                "
              >
                加载建筑
              </button>
              <button
                @click="
                  async () => {
                    await addRoadsLayer(scene.value)
                    refreshLayerList()
                  }
                "
              >
                加载道路
              </button>
            </div>
          </div>
        </div>

        <button class="btn navigation" title="导航" @click="toggleNavigation">...</button>
        <!-- ...other buttons... -->
      </div>
    </header>
  </div>
</template>

<style scoped>
/* 可根据现有样式微调下拉样式 */
.layer-dropdown button {
  background: rgba(255, 255, 255, 0.06);
  color: #fff;
  border-radius: 4px;
  padding: 4px 8px;
  border: none;
  cursor: pointer;
}
.layer-dropdown input {
  width: 16px;
  height: 16px;
}
</style>
